package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.*;
import com.itheima.common.BaseContext;
import com.itheima.dao.*;
import com.itheima.dto.OrdersDto;
import com.itheima.exception.CustomException;
import com.itheima.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressBookDao addressBookDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    @Transactional
    public void sumbit(Orders orders) {
        //原因：要根据订单明细表中的商品单价和数量计算订单总金额
        //1.获取当前登录的用户id，查询用户信息 判断用户是否存在
        Long userId = BaseContext.getCurrentId();
        log.info("==============================" + userId);
        User user = userDao.selectById(userId);
        if (user == null) {
            throw new CustomException(0, "请先登录，再下单！");
        }

        //2.根据地址id判断下单地址是否存在  	如果不存在，则无法下单
        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException(0, "请填写地址后再下单！");
        }

        //3.根据用户id获取当前用户购物车列表数据 判断用户购物车是否有商品 没有，则无法下单
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> carts = shoppingCartDao.selectList(wrapper);
        if (carts == null || carts.size() == 0) {
            throw new CustomException(0, "请选择商品后再下单！");
        }

        //提前手动生成订单id
        long orderId = IdWorker.getId();
        //BigDecimal：这种类型精度不会丢失  使用原子类型：保证并发环境下，线程安全
        //BigDecimal sumAccount = new BigDecimal(0);
        AtomicInteger sumAccount = new AtomicInteger(0);


        //4.保存订单下的商品信息到订单明细表 order_detail中 将当前用户 购物车中商品转存到 订单详情表中，并同时设置关联的订单id
        carts.stream().forEach(cart -> {
            //计算总金额
            sumAccount.addAndGet((cart.getAmount().multiply(new BigDecimal(cart.getNumber()))).intValue());

            //a:创建订单详情下的商品对象 OrderDetail
            OrderDetail orderDetail = new OrderDetail();

            //b：将cart对象中属性数据复制到 orderDetail对象中
            BeanUtils.copyProperties(cart, orderDetail);

            //c：设置订单项商品关联的订单id
            orderDetail.setOrderId(orderId);

            //d：将每一个订单项商品存入到order_detail中
            orderDetailDao.insert(orderDetail);
        });

        //5.保存订单基本信息到订单表 orders中
        //补全orders字段
        //1.订单id
        orders.setId(orderId);

        //2.订单号 订单号使用UUID随机生成一个唯一的字符串
        orders.setNumber(UUID.randomUUID().toString());

        //3.订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);

        //4.下单用户id
        orders.setUserId(userId);

        //5.地址id        前端传递
        //6.下单时间       使用当前时间
        orders.setOrderTime(LocalDateTime.now());

        //7.结账时间
        orders.setCheckoutTime(LocalDateTime.now());

        //8.支付方式 1微信，2支付宝  前端传递

        //9.实收金额
        orders.setAmount(new BigDecimal(sumAccount.intValue()));

        //10备注 前端传递

        //11.用户名
        orders.setUserName(user.getName());

        //12.手机号
        orders.setPhone(addressBook.getPhone());

        //13.地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );

        //14.收货人
        orders.setConsignee(addressBook.getConsignee());

        ordersDao.insert(orders);

        //6.情况 当前用户购物车数据
        shoppingCartDao.delete(wrapper);
    }

    @Override
    public Page<OrdersDto> orderPageDetail(Integer page, Integer pageSize) {
        Long userId = BaseContext.getCurrentId();
        //log.info("=============================="+userId);
        User user = userDao.selectById(userId);
        if (user == null) {
            throw new CustomException(0, "请先登录，再下单！");
        }
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        ordersWrapper.eq(Orders::getUserId, userId);
        ordersWrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersDao.selectPage(ordersPage, ordersWrapper);
        List<Orders> orders = ordersPage.getRecords();
        Page<OrdersDto> ordersDtoPage = new Page<>();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders order : orders) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            orderDetailWrapper.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = orderDetailDao.selectList(orderDetailWrapper);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtos);
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        //ordersDtoPage.setTotal(ordersPage.getTotal());
        return ordersDtoPage;
    }

    @Override
    public Page<Orders> ordersPage(Integer page, Integer pageSize, String number, Date beginTime, Date endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(number != null, Orders::getNumber, number);
        wrapper.gt(beginTime != null, Orders::getOrderTime, beginTime);
        wrapper.lt(endTime != null, Orders::getOrderTime, endTime);
        ordersDao.selectPage(ordersPage, wrapper);
        return ordersPage;
    }
}
